#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "hi_gpio.h"
#include "hi_io.h"
#include "hi_adc.h"
#include "hi_errno.h"

#define LED_INTERVAL_TIME_US 200000
#define LED_TASK_STACK_SIZE 4096
#define LED_TASK_PRIO 25
#define LED_TEST_GPIO 1
#define SKEW_DETECT_GPIO 12
enum LedState {
LED_ON = 0,
LED_OFF,
LED_SPARK,
};
#define SKEW_DETECT_ON 1
#define SKEW_DETECT_OFF 0

static void SkewDetectInit()
{
    // LED GPIO初始化
    IoTGpioInit(LED_TEST_GPIO);
    hi_io_set_func(LED_TEST_GPIO, HI_IO_FUNC_GPIO_1_GPIO);
    IoTGpioSetDir(LED_TEST_GPIO, IOT_GPIO_DIR_OUT);
    hi_io_set_pull(LED_TEST_GPIO, HI_IO_PULL_UP);
    IoTGpioSetOutputVal(LED_TEST_GPIO, LED_OFF);

    // 倾斜传感器GPIO初始化
    IoTGpioInit(SKEW_DETECT_GPIO);
    hi_io_set_func(SKEW_DETECT_GPIO, HI_IO_FUNC_GPIO_12_GPIO);
    IoTGpioSetDir(SKEW_DETECT_GPIO, IOT_GPIO_DIR_IN);
    hi_io_set_pull(SKEW_DETECT_GPIO, HI_IO_PULL_UP);
}

static void *skewDetectTask(const char *arg)
{
    unsigned char ucType;
    (void)arg;
    while (1) {
        ucType = 0;
        IoTGpioGetInputVal(SKEW_DETECT_GPIO, &ucType);
        printf("SKEW_DETECT_GPIO %d\n", ucType);  
        if(ucType == SKEW_DETECT_ON) {
            IoTGpioSetOutputVal(LED_TEST_GPIO, LED_ON);
        } else {
            IoTGpioSetOutputVal(LED_TEST_GPIO, LED_OFF);
        }
        usleep(LED_INTERVAL_TIME_US);
    }
    
    return NULL;
}

static void skewDetectEntry(void)
{
    osThreadAttr_t attr;

    SkewDetectInit();

    attr.name = "SkewDetectTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = LED_TASK_STACK_SIZE;
    attr.priority = LED_TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)skewDetectTask, NULL, &attr) == NULL) {
        printf("[SkewDetectEntry] Failed to create SkewDetectTask!\n");
    }
}

SYS_RUN(skewDetectEntry);
